﻿using System.Net.Http;
using System.Threading.Tasks;
using System.Xml.Serialization;

namespace Murry.DataStore.WebApiDB
{
    /// <summary>
    /// ReadAsAsync is too picky for some API's.
    /// </summary>
    public static class HttpContentExtensions
    {
        /// <summary>
        /// ReadAsAsync is too picky for some API's.  Bypass the normal de-serialization if XML. 
        /// </summary>
        /// <remarks>
        /// If content is XML, assumes XmlSerializer will be used to de-serialize object.
        /// </remarks>
        /// <typeparam name="T">Type of object to return.</typeparam>
        /// <param name="content">Content to read.</param>
        /// <returns>Task</returns>
        public static Task<T> ReadAsAsyncIgnoreXmlEncoding<T>(this HttpContent content)
        {
            if (content.Headers.ContentType.MediaType != "text/xml")
            {
                return content.ReadAsAsync<T>();
            }

            return Task<T>.Factory.StartNew(() =>
            {
                using (var stream = content.ReadAsStreamAsync().Result)
                {
                    var serializer = new XmlSerializer(typeof(T));
                    return (T)serializer.Deserialize(stream);
                }
            });
        }
    }
}
